﻿using OcmKeep;
using System;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace zwWitLink
{
    [System.Runtime.InteropServices.ComVisible(true)]

    public partial class zwForm : Form
    {
        [System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint = "keybd_event")]
        public static extern void keybd_event(
            byte bVk,
            byte bScan,
            int dwFlags,  //0: DOWN, 2: UP  
            int dwExtraInfo  //Default: 0  
        );
        string auto_key = "0";
        //const string LOADURI = "file:///C:/Users/ocm/Desktop/1.html";
        string LOADURI = "tp5.com/admin/main/login.html";
        string server = "";
        IniHelper ini;
        ocmctr.UmfCtr umf;
        ocmctr.FingerCtr finger = new ocmctr.FingerCtr();
        Color unlink = Color.FromArgb(255, 66, 56);
        Color link = Color.FromArgb(27, 162, 97);
        Color mouseleave = Color.FromArgb(230, 231, 232);
        Option optionForm = new Option();
        PictureBox fgPic = new PictureBox();
        byte[] fingerTemp = new byte[512];
        Point mouseOff; bool canMove = false;
        int sysInt = 0;
        bool umflink = false;
        bool fingerlink = false;
        public delegate void updateTipHandler(string msg);
        public delegate void CallBack(int state);
        const string defaultCardNo = "6F636D000000000000000000000000AB";
        string oldcardNo = "null";
        string fingerImgPath = "";

        WebKit.WebKitBrowser webBrowser;
        public zwForm()
        {
            if (ParamLoad()) {
                InitializeComponent();
                UILoad();
            }
            
        }
        protected override CreateParams CreateParams
        {
            get
            {
                const int WS_MINIMIZEBOX = 0x00020000;  // Winuser.h中定义  
                CreateParams cp = base.CreateParams;
                cp.Style = cp.Style | WS_MINIMIZEBOX;   // 允许最小化操作  
                return cp;
            }
        }  
        void UILoad()
        {
            this.FormClosing += zwForm_FormClosing;
            this.Load += zwForm_Load;
            toolBar.DoubleClick += zwForm_DoubleClick;
            btnClose.MouseEnter += btnClose_MouseEnter;
            btnClose.MouseLeave += btnClose_MouseLeave;
            btnMin.Click += btnMin_Click;
            btnMin.MouseEnter += btnMin_MouseEnter;
            toolBar.MouseDown += toolBar_MouseDown;
            toolBar.MouseMove += toolBar_MouseMove;
            toolBar.MouseUp += toolBar_MouseUp;
            btnOption.MouseEnter += btnOption_MouseEnter;
            btnOption.Click += btnOption_Click;
        }

        void zwForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            closeDev();
        }
       public Boolean ParamLoad()
        {
            string Current = Directory.GetCurrentDirectory();
            string path = Current + "/Config/config.ini";
            DirectoryInfo dir = Directory.CreateDirectory(Current + "/Config");
            FileStream file = File.Open(path, FileMode.OpenOrCreate);
            file.Close();
            ini = new IniHelper(path);
            string system = ini.ReadValue("Setting", "system");
            server = ini.ReadValue("Setting", "server");
            try
            {
                umf = new ocmctr.UmfCtr();
            }catch(Exception e){                
                Process.Start(Application.StartupPath + "\\中未密钥.exe");
                ini.WriteValue("Setting", "auto_key", "1");
                return false;
               // MessageBox.Show(e.Message,"",MessageBoxButtons.OK,MessageBoxIcon.Error);
            }
            auto_key = ini.ReadValue("Setting", "auto_key");
           
            if (!int.TryParse(system, out sysInt))
            { 
                sysInt = 0;
                ini.WriteValue("Setting", "system", "0");
            }
            systemRender();
            if (server.Length <= 1)
            {
                //server = "tp5.com";
                ini.WriteValue("Setting", "server", server);
            }
            if (auto_key != "1")
            {
                ini.WriteValue("Setting", "auto_key", "0");
            }
            LOADURI = "http://" + server + "/admin/main/login/type/auto";
            
            return true;
        }
          
        public string WriteAuth(string auth)
        {
            StringBuilder temp = new StringBuilder(auth);
            for (int i = temp.Length; i < 8; i++)
            {
                temp.Insert(0, "0");
            }
            return umf.writeAuth("6F636D000000000000000000" + temp.ToString().Substring(0, 8)) + "";
        }
        public string ReadAuth()
        {
            object cardno = null;
            int res = 0;
            string result = "";
            res = umf.readAuth(ref cardno);
            if (res == 0)
            {
                result = cardno.ToString().Substring(24, 8).Replace("0","");
                if (result.Length == 0) return "00000000";
            }
            else
            {
                result = "-3";
            }
            return result;
        }

        public string ReadCupNo()
        {
            object cardno = null;
            int res = 0;
            string result = "";
            string tmp = "";
            res = umf.readCupNo(ref cardno);
            if (res == 0)
            {
                tmp = cardno.ToString();
                if (tmp.Equals("00000000")) result = "没有查询到";
                else
                {
                    string restmp = tmp.Substring(0, 2);
                    switch (restmp)
                    {
                        case "00": result += "女"; break;
                        case "01": result += "男"; break;
                        case "02": result += "C"; break;
                        case "03": result += "D"; break;
                        case "04": result += "E"; break;
                        case "05": result += "F"; break;
                        case "06": result += "G"; break;
                    }
                    result += tmp.Substring(3, 1) + tmp.Substring(5, 1) + tmp.Substring(7, 1);
                }
            }
            else
            {
                result = res.ToString();
            }
            return result;
        }

        void systemRender()
        {

            StartAutoRead();
        }
        void zwForm_DoubleClick(object sender, EventArgs e)
        {
            if(this.WindowState==FormWindowState.Maximized){
                this.WindowState = FormWindowState.Normal;
            }else{
                this.WindowState = FormWindowState.Maximized;
            }
            webBrowser.Refresh();
        }

        void btnOption_MouseEnter(object sender, EventArgs e)
        {
            toolTip.Show("参数设置", btnOption, 1000);
        }


        void toolBar_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                canMove = false;
            }
        }

        void toolBar_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left && canMove)
            {
                Point mouseSet = Control.MousePosition;
                mouseSet.Offset(mouseOff.X, mouseOff.Y);  //设置移动后的位置  
                Location = mouseSet;
            }
        }

        void toolBar_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                mouseOff = new Point(-e.X, -e.Y);
                canMove = true;
            }
        }

        void btnMin_MouseEnter(object sender, EventArgs e)
        {
            toolTip.Show("最小化", btnMin, 1000);
        }

        void btnMin_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
        }

        void btnClose_MouseLeave(object sender, EventArgs e)
        {
            btnClose.Image = Properties.Resources.close;
            btnClose.BackColor = mouseleave;
        }

        void btnClose_MouseEnter(object sender, EventArgs e)
        {
            btnClose.Image = Properties.Resources.closelight;
            btnClose.BackColor = Color.FromArgb(251, 97, 85);
        }

        void zwForm_Load(object sender, System.EventArgs e)
        {
            webBrowser = new WebKit.WebKitBrowser();
            webBrowser.Dock = DockStyle.Fill;
            panelbox.Controls.Add(webBrowser);
            webBrowser.DocumentCompleted += webBrowser_DocumentCompleted;
            init();
         
        }

        void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            webBrowser.GetScriptManager.ScriptObject = new JsInterface(this);
        }

        private void init()
        {
            checkDevThread();
            webBrowser.Url = new System.Uri(LOADURI);
        }

        /// <summary>
        /// 设置员工能否开柜
        /// </summary>
        /// <param name="value">1能，0不能</param>
        /// <returns></returns>
        public string StaffCardSet(string value)
        {
            if (value == null || value.Equals("1"))
            {
                string num = "00000000000000000000000000000000";
                int res = umf.writeCard(num, 9);
                return res.ToString();
            }
            else
            {
                string num = "6F636D0C000000000000000000000000";
                int res = umf.writeCard(num, 9);
                return res.ToString();
            }
        }

        /// <summary>
        /// 读查询卡
        /// </summary>
        /// <returns></returns>
        public string ReadNoNumber()
        {
            int res = 0;
            object data = null;
            res = umf.readCard(ref data,8);
            if (res == 0)
            {
                if (data.ToString().Substring(0, 24).Equals("333333333333333333333333"))
                {
                    return StrReverseToDex(data.ToString().Substring(24, 8));
                }
                else
                {
                    return "-12";
                }
            }
            else return res.ToString();
        }

        private void checkDevThread()
        {
            ThreadPool.QueueUserWorkItem(checkUmf, "");
            //ThreadPool.QueueUserWorkItem(checkFinger, "");
        }
        private void checkUmf(object state)
        {
            bool res = false;
            while (!umflink)
            {
                try
                {
                    res = umf.openDev(0, 0, 0);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.StackTrace);
                }
                if (res)
                {
                    umflink = true;
                    umfState.BackColor = link;
                }
                Thread.Sleep(1000);
            }
        }


        public string ClearCard()
        {
            int res = 0;
            res = umf.clearCup();
            if (res == 0) return "0";
            return res.ToString();
        }


        private void checkFinger(object state)
        {
            int ret = -1;
            while (!fingerlink)
            {
                try
                {
                    ret = finger.openDev();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.StackTrace);
                }
                if (ret == 0)
                {
                    fingerlink = true;
                    fingerState.BackColor = link;
                }
                Thread.Sleep(1000);
            }
        }

        private void btnDevReset_Click(object sender, EventArgs e)
        {
            Reconncet();
        }

        public void StartAutoRead()
        {
            //if (running) return;
            //running = true;
            //new Thread(new ThreadStart(runPwd)).Start();
            umf.startRead();
        }
        public void StopAutoRead()
        {
            running = false;
            umf.stopRead();
        }

        private void closeDev()
        {
            try
            {
                //finger.closeDev();
                StopAutoRead();
                umf.closeDev();
            }
            catch (Exception ex)
            {

            }
        }
        public string Reconncet()
        {
            closeDev();
            string res = "";
            if (umf.openDev(0, 0, 0))
            {
                umflink = true;
                res = "0";
                StartAutoRead();
            }
            else
            {
                if (umf.openDev(0, 0, 0))
                {
                    umflink = true;
                    res = "0";
                    StartAutoRead();
                }
                else res = "1";
            }
            return res;
        }

        /// <summary>
        /// 制卡
        /// </summary>
        public string MakeCard()
        {
            string isfuc = IsFuc("");
            if (!isfuc.Equals("0")) return isfuc;
            int res = umf.writeCard(defaultCardNo);
            if (res == 0) return "0";
            return res.ToString();
            //if (res == 0) updateTip("制卡成功");
            //else updateTip("制卡失败");
        }

        public string CardError(int type) { 
            switch(type){
                case -1:
                    return "寻卡错误";
                case -2:
                    return "校验失败";
                case -3:
                    return "制卡失败";
                case -4:
                    return "读卡错误";
                case -5:
                    return "加密错误";
                default:
                    return "未知错误";
            }
        }

        public string RestCard()
        {
            int res = 0;
            string isfuc = IsFuc("");
            if (isfuc.Equals("0"))
            {
                res = umf.writeCard(defaultCardNo);
            }
            if (res == 0)
            {
                res = umf.writeCard("00000000000000000000000000000000",9);
                if (res == 0)
                {
                    res = umf.writeAuth("6F636D00000000000000000000000000");
                    if (res == 0) return "0";
                    else return res.ToString();
                }
                else
                {
                    return res.ToString();
                }
            }
            else return res.ToString();

        }

        public string MakeNoCupCard() {
            string isfuc = IsFuc("");
            if (!isfuc.Equals("0")) return isfuc;
            int res = umf.writeCard("000000000000000000000000000000AB");
            if (res == 0) return "0";
            return res.ToString();
        }


        /// <summary>
        /// 制查询卡 
        /// @param 10位的10进制 卡号
        /// </summary>
        public string QueryCard(string cardno)
        {
            string isfuc = IsFuc("query");
            if (!isfuc.Equals("0")) return isfuc;
            long cInt = long.Parse(cardno);
            if (cardno.ToString().Length != 10) return "-2";
            int res = umf.writeCard("222222222222222222222222" + DecToHexReverse(cInt.ToString("x2")));
            if (res == 0) return "0";
            return res.ToString();
            //if (res == 0) updateTip("制卡成功");
            //else updateTip("制卡失败");
        }

        public string StateCard() {
            string isfuc = IsFuc("state");
            if (!isfuc.Equals("0")) return isfuc;
            int res = umf.writeCard("33333333333333333333333300000000");
            if (res == 0) return "0";
            return res.ToString();
        }

        bool IsAuto()
        {
            return sysInt == 1;
        }
        public string GetError(string err)
        {
            switch (err)
            {
                case "-1": return "寻卡失败";
                case "-2": return "校验失败";
                case "-3": return "制卡失败";
                case "-4": return "读卡失败";
                case "-5": return "加密失败";
                case "-6": return "清柜失败";
                case "-11": return "功能卡，不能制卡";
                case "-12": return "不是查询卡";
                case "-13": return "参数错误，应传入8位16进制";
                case "-15": return "指纹录取失败";
                default: return "未知错误";
            }
        }
        bool running = false;
        string beforepwdCardno = "";
        private void runPwd()
        {
            int ret = 0;
            object cardno = "";
            string tempcardno = "1";
            while (running)
            {
                ret = umf.getCardNo(ref cardno);
                if (ret != 0) { beforepwdCardno = "1"; continue; }
                tempcardno = cardno.ToString();
                if (tempcardno.Equals(beforepwdCardno)) continue;
                beforepwdCardno = tempcardno;
                ret = umf.writeKey();
                if (ret == 0)
                {
                    SendKeys.SendWait(StrReverseToDex(cardno.ToString()));
                    umf.bee(20);
                }
                else
                {
                    umf.bee(50);
                    Thread.Sleep(200);
                    umf.bee(50);
                }
            }
        }
        //public string StrReverseToDex(string strSb)
        //{
        //    char[] result = new char[8];
        //    result[0] = strSb[6];
        //    result[1] = strSb[7];
        //    result[2] = strSb[4];
        //    result[3] = strSb[5];
        //    result[4] = strSb[2];
        //    result[5] = strSb[3];
        //    result[6] = strSb[0];
        //    result[7] = strSb[1];
        //    StringBuilder temp = new StringBuilder(Convert.ToInt64(new string(result), 16) + "");
        //    for (int i = temp.Length; i < 10; i++)
        //    {
        //        temp.Insert(0, "0");
        //    }
        //    return temp.ToString();
        //}
        /// <summary>
        /// 读卡
        /// </summary>
        public string ReadCard()
        {
            object cardno = null;
            int res = 0;
            int trynum = 2;
            string result = "";
            string isfuc = IsFuc("");
            if (isfuc.Equals("0"))
            {
                res = umf.writeCard("6F636D000000000000000000000000AB");
            }
            if (res == 0)
            {
                res = umf.getCardNo(ref cardno);
                if (res == 0)
                {
                    result = StrReverseToDex(cardno.ToString());
                }
                else
                {
                    result = res.ToString();
                }
            }
            else
            {
                result = "-4";
            }
            return result;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="num">柜子编号</param>
        /// <param name="gender">1男 2女</param>
        /// <returns></returns>
        public string EditNoCard(string num, string gender)
        {
            string isfuc = IsFuc("");
            if (!isfuc.Equals("0")) return isfuc;
            int n = 0;
            StringBuilder sb = new StringBuilder();
            string sexStr = "0" + gender;
            string tmp = num;
            string editcardnoStr = "";
            if (int.TryParse(num, out n) && num.Length <= 3)
            {
                while (tmp.Length != 3)
                {
                    tmp = "0" + tmp;
                }
                sb.Append("111111111111111111111111")
                           .Append(sexStr).Append("0").Append(tmp[0])
                           .Append("0").Append(tmp[1])
                           .Append("0").Append(tmp[2]);
                editcardnoStr = sb.ToString();
                return umf.writeCard(editcardnoStr).ToString();
            }
            else
            {
                return "-1";
            }
        }

        /// <summary>
        /// 录指纹
        /// </summary>
        public void SignInFinger(object state)
        {
            if (fingerlink)
            {
                ThreadPool.QueueUserWorkItem(erollfp1, state);
            }
            else
            {
                updateTip("指纹设备未连接");
            }
        }

        bool getfp1 = false;
        private unsafe void erollfp1(object state)
        {
            byte[] temp = new byte[512];
            int ret = 0;
            byte[] ImgData = new byte[256 * 288];
            finger.closeDev();
            ret = finger.connect_usb();
            if (ret != 0)
            { goto ENDERR; }
            //获取指纹图像 
            if (finger.getchar(1, 2000, fgPic.Handle, ref ImgData) != 1)
            { goto ENDERR; }
            else
            {
                getfp1 = true;
            }
        ENDERR:
            finger.connect_close();
            return;
        }
        bool isRegister = false;
        private unsafe void erollfp2(object state)
        {
            if (!getfp1)
            {
                updateTip("请先录取指纹1");
                return;
            }
            byte[] temp = new byte[512];
            int tempLen = 0;
            int ret = 0;
            byte[] ImgData = new byte[256 * 288];
            //确认指纹图像
            if (finger.getchar(2, 2000, fgPic.Handle, ref ImgData) != 1)
            { goto ENDERR; }
            Thread.Sleep(200);
            /****************上传指纹模板*********/
            ret = finger.upChar(ref temp, ref tempLen);
            if (ret != 0)
            { updateTip(finger.getError(ret)); goto ENDERR; }
            else
            {
                fingerTemp = temp;
                isRegister = true;
                //录取成功
            }
        ENDERR:
            finger.connect_close();
            return;
        }

        private void updateTip(string msg)
        {
            return;
            if (tip.InvokeRequired == true)
            {
                updateTipHandler set = new updateTipHandler(updateTip);
                label2.Invoke(set, new object[] { msg });
            }
            else
            {
                tip.Text = msg;
            }
        }


        private string DecToHexReverse(string dec)
        {
            char[] result = new char[8];
            result[0] = dec[6];
            result[1] = dec[7];
            result[2] = dec[4];
            result[3] = dec[5];
            result[4] = dec[2];
            result[5] = dec[3];
            result[6] = dec[0];
            result[7] = dec[1];
            return new string(result);
        }

        private string StrReverseToDex(string strSb)
        {
            char[] result = new char[8];
            result[0] = strSb[6];
            result[1] = strSb[7];
            result[2] = strSb[4];
            result[3] = strSb[5];
            result[4] = strSb[2];
            result[5] = strSb[3];
            result[6] = strSb[0];
            result[7] = strSb[1];
            StringBuilder temp = new StringBuilder(Convert.ToInt64(new string(result), 16) + "");
            for (int i = temp.Length; i < 10; i++)
            {
                temp.Insert(0, "0");
            }
            return temp.ToString();
        }


        private void btnRefresh_Click(object sender, EventArgs e)
        {
            webBrowser.Refresh();
        }


        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        const int Guying_HTLEFT = 10;
        const int Guying_HTRIGHT = 11;
        const int Guying_HTTOP = 12;
        const int Guying_HTTOPLEFT = 13;
        const int Guying_HTTOPRIGHT = 14;
        const int Guying_HTBOTTOM = 15;
        const int Guying_HTBOTTOMLEFT = 0x10;
        const int Guying_HTBOTTOMRIGHT = 17;

        protected override void WndProc(ref Message m)
        {
            switch (m.Msg)
            {
                case 0x0084:
                    base.WndProc(ref m);
                    Point vPoint = new Point((int)m.LParam & 0xFFFF,
                        (int)m.LParam >> 16 & 0xFFFF);
                    vPoint = PointToClient(vPoint);
                    if (vPoint.X <= 5)
                        if (vPoint.Y <= 5)
                            m.Result = (IntPtr)Guying_HTTOPLEFT;
                        else if (vPoint.Y >= ClientSize.Height - 5)
                            m.Result = (IntPtr)Guying_HTBOTTOMLEFT;
                        else m.Result = (IntPtr)Guying_HTLEFT;
                    else if (vPoint.X >= ClientSize.Width - 5)
                        if (vPoint.Y <= 5)
                            m.Result = (IntPtr)Guying_HTTOPRIGHT;
                        else if (vPoint.Y >= ClientSize.Height - 5)
                            m.Result = (IntPtr)Guying_HTBOTTOMRIGHT;
                        else m.Result = (IntPtr)Guying_HTRIGHT;
                    else if (vPoint.Y <= 5)
                        m.Result = (IntPtr)Guying_HTTOP;
                    else if (vPoint.Y >= ClientSize.Height - 5)
                        m.Result = (IntPtr)Guying_HTBOTTOM;
                    break;
                case 0x0201:                //鼠标左键按下的消息   
                    m.Msg = 0x00A1;         //更改消息为非客户区按下鼠标   
                    m.LParam = IntPtr.Zero; //默认值   
                    m.WParam = new IntPtr(2);//鼠标放在标题栏内   
                    base.WndProc(ref m);
                    break;
                default:
                    base.WndProc(ref m);
                    break;
            }
        }
        private string IsFuc(string type)
        {
            object cardno = null;
            int res = 0;
            res = umf.readCard(ref cardno);
            if (res != 0) return res.ToString();
            string cardStr = cardno.ToString();
            if (type.ToLower().Equals("query"))
            {
                if (!cardStr.Contains("222222222222222222222222"))
                {
                    return "-11";
                }
            }
            else if (type.ToLower().Equals("state"))
            {
                if (!cardStr.Contains("333333333333333333333333"))
                {
                    return "-11";
                }
            }
            else
            {
                if (cardStr.Equals("6F636D00000000000000000000000000") || cardStr.Contains("222222222222222222222222") || cardStr.Contains("333333333333333333333333"))
                {
                    return "-11";
                }
            }
            return "0";
        }

        void btnOption_Click(object sender, EventArgs e)
        {
            optionForm.server = server;
            optionForm.systemChanged += new EventHandler(
                (sender1, e1) =>
                {
                    server = optionForm.server;
                    systemRender();
                    LOADURI = "http://" + optionForm.server + "/admin/main/login/type/auto?" + DateTime.Now.Ticks;
                    webBrowser.Navigate(LOADURI);
                    ini.WriteValue("Setting", "system", optionForm.server.ToString());
                }
            );
            optionForm.ShowDialog();
        }

        private void label3_Click(object sender, EventArgs e)
        {

        }
    }



}
